from django.shortcuts import render,redirect,reverse,HttpResponse
from django.http.response import JsonResponse
import string
import random
from django.core.mail import send_mail
from .models import CaptchaModel
from django.views.decorators.http import require_http_methods
from .forms import RegisterForm,LoginForm
from django.contrib.auth import get_user_model,login,logout

User = get_user_model()

# Create your views here.
@require_http_methods(['GET','POST'])
def xcj_login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remeber = form.cleaned_data.get('remember')
            user = User.objects.filter(email=email).first()
            if user and user.check_password(password):
                # 登录
                login(request,user)

                # 没设置记住我，则设置过期时间为0,反之则什么不做，默认两周过期时间
                if not remeber:
                    request.session.set_expiry(0)
                return render(request,'index.html',context={"username":user})
            else:
                print('邮箱或者密码错误')
                form.add_error('email','邮箱或者密码错误')
                return render(request,'login.html',context={'form':form})
                # return redirect(reverse('xcjauth:login'))
        else:
            form.add_error('email','邮箱或者密码错误')
            return render(request,'login.html',context={'form':form})

@require_http_methods(['GET'])
def xcjlogout(request):
    logout(request)
    return redirect('/')



@require_http_methods(['GET','POST'])
def register(request):
    if request.method == 'GET':
        return  render(request,'register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            User.objects.create_user(email=email,username=username,password=password)
            return redirect(reverse('xcjauth:login'))
        else:
            print(f"注册失败,错误消息:{form.errors}")
            # return redirect(reverse('xcjauth:register'))
            form.add_error('email', '信息有误')
            return render(request, 'register.html', context={'form': form})
            # return render(request,'register.html',context={"form":form.errors})

def send_email_captcha(request):
    # ?email=xxx
    email = request.GET.get('email')
    if not email:
        return JsonResponse({"code":400,"message":"必须传递邮箱！"})
    # 随机4位阿拉伯数字
    captcha = "".join(random.sample(string.digits,4))
    CaptchaModel.objects.update_or_create(email=email,defaults={'captcha':captcha})
    send_mail("小菜鸡博客注册验证码",message=f"您的注册验证码是:{captcha}",recipient_list=[email],from_email=None)
    return JsonResponse({"code":200,"message":"邮箱验证码发送成功！！！"})
